<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import appMenuServiceApi from "@/api/modules/org/bean/app-menu";
import { SYSTEM_CONFIG } from "@/config/system";

const props = defineProps({
  showCheckbox: {
    type: Boolean,
    default: false
  },
  // 树数据是否自定义，
  isCustomTreeData: {
    type: Boolean,
    default: false
  },
  customTreeData: {
    type: Array
  }
});
watch(
  () => props.customTreeData,
  val => {
    AppMenuTreeState.treeData = val as [];
  }
);

const appMenuTreeRef = ref();

const AppMenuTreeState = reactive({
  props: {
    label: "menuName",
    children: "children"
  },
  treeData: [],
  /**异步树加载 */
  loadNode: () => {
    appMenuServiceApi.queryList(null, { appId: SYSTEM_CONFIG.APP_ID }).then((res: any) => {
      //获取首级菜单
      const treeNodeArr = res.data.filter((item: any) => item.parentMenuId == null);
      if (treeNodeArr.length == 0) return [];
      treeNodeArr.forEach((item: any) => handleTreeData(item, res.data));
      AppMenuTreeState.treeData = treeNodeArr;
    });
  }
});

/**
 * 处理树形数据
 */
function handleTreeData(parentMneu: any, resourceData: any[]) {
  const childrenArr = resourceData.filter(item => item.parentMenuId == parentMneu.menuId);
  if (childrenArr && childrenArr.length > 0) {
    childrenArr.forEach(item => handleTreeData(item, resourceData));
    parentMneu.children = childrenArr;
  }
}

onMounted(() => {
  if (!props.isCustomTreeData) {
    AppMenuTreeState.loadNode();
  }
});

defineExpose({
  getCheckedNodes: () => {
    return appMenuTreeRef.value.getCheckedNodes();
  },
  setCheckedKeys: (keys: Array<String>) => {
    return appMenuTreeRef.value.setCheckedKeys(keys);
  }
});
</script>
<template>
  <el-tree
    ref="appMenuTreeRef"
    highlight-current
    :show-checkbox="showCheckbox"
    :data="AppMenuTreeState.treeData"
    node-key="menuId"
    :props="AppMenuTreeState.props"
    :default-expanded-keys="['10000']"
  />
</template>
